package org.gap.wizards.world.actions;

import java.util.List;

import org.gap.wizards.items.Item;
import org.gap.wizards.items.construction.ElixerInstructions;
import org.gap.wizards.items.construction.MakingStation;
import org.gap.wizards.pc.PlayerCharacter;
import org.gap.wizards.views.InventorySelectionView;
import org.gap.wizards.views.MessageOutput;
import org.gap.wizards.world.Location;
import org.gap.wizards.world.WorldAction;

public class CreateElixerAction implements WorldAction {
	private PlayerCharacter pc;
	private MessageOutput output;
	private MakingStation alchemyLab;
	private final Location location;
	private final InventorySelectionView equipmentView;

	public CreateElixerAction(PlayerCharacter pc, MessageOutput output, InventorySelectionView equipmentView, Location location) {
		this.pc = pc;
		this.output = output;
		this.equipmentView = equipmentView;
		this.location = location;
	}

	@Override
	public void perform() {
		if (isAlechemyLabHere()) {
			output.draw();
			List<Item> itemsOfType = pc.getInventory().itemsOfType(ElixerInstructions.class);
			if (itemsOfType.isEmpty()) {
				output.addMessage("You don't have any elixer instructions to follow?");
				return;
			} else {
				output.addMessage("Select an elixer to make?");
			}
			equipmentView.setItems(itemsOfType);
			List<Item> selection = equipmentView.getSelection();
			if (selection.isEmpty()) {
				return;
			}
			ElixerInstructions instructions = (ElixerInstructions) selection.get(0);
			Item[] availableItems = pc.getInventory().allItems().toArray(new Item[selection.size()]);
			if (!instructions.usableItems(availableItems)) {
				output.addMessage("You need all the components to make the " + instructions + ".");
				return;
			}
			alchemyLab.addInstructions(instructions);
			Item elixer = alchemyLab.make(pc, availableItems);
			for (Item each : instructions.getComponents()) {
				pc.getInventory().removeItem(each);
			}
			if (elixer == null) {
				output.addMessage("You failed to create the " + instructions + ".");
			} else {
				output.addMessage("You worked your magic and created the " + instructions + ".");
				pc.getInventory().addItem(elixer);
			}
		}
	}

	private boolean isAlechemyLabHere() {
		List<Object> allFromLocation = location.getAllFromLocation(location.getCharacterLocation());
		for (Object each : allFromLocation) {
			if (each instanceof MakingStation) {
				alchemyLab = (MakingStation)each;
				return true;
			}
		}
		return false;
	}

}
